package com.lovemanai.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.apache.struts2.ServletActionContext;

import com.lovemanai.dao.DbDao;
import com.lovemanai.tools.common.CommonUtils;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class UploadAction extends ActionSupport {

	private DbDao ddDao = new DbDao();
	
	private static final long serialVersionUID = 1L;

	private File upload;//上传文件域
	private String uploadFileName;//上传文件名
	private String uploadContentType;//上传文件类型
	private String title;//标题 
	
	private String savePath;//文件在服务器保存路径
	
	public String getSavePath() {
		return ServletActionContext.getServletContext().getRealPath(savePath);
	}

	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}



	public File getUpload() {
		return upload;
	}



	public void setUpload(File upload) {
		this.upload = upload;
	}



	public String getUploadFileName() {
		return uploadFileName;
	}



	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}



	public String getUploadContentType() {
		return uploadContentType;
	}



	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	


	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	@Override
	public String execute() throws Exception {
		//上传文件保存到用户个人文件夹
		Map<String,Object> session = ActionContext.getContext().getSession();
		//用户名唯一，用户名作为子目录
		File destDir = new File("F:/temp/" + (String) session.get("userName"));
		//链式创建目录
		destDir.mkdirs();
		String fileName = CommonUtils.uuid() + "_" + getUploadFileName();//使用uuid防止用户上传同名文件
		File filePath = new File(destDir	 + "/" + fileName );
		//获取写入到服务器的输出
		FileOutputStream fos = new FileOutputStream(filePath);
		//本地上传到服务器的输入流
		FileInputStream fis = new FileInputStream(getUpload());
		
		//使用IOUtils将文件写入到服务器完成上传
		IOUtils.copy(fis, fos);
		
		if(fos != null) fos.close();
		if(fos != null) fis.close();
		
		insertFile(filePath);//将文件信息存入数据库
		
		return SUCCESS;
	}
	
	/**
	 * 将文件信息存入数据库
	 * @param filePath 文件在服务器端存储的路径
	 */
	public void insertFile(File filePath) {
		ActionContext acx = ActionContext.getContext();
		//文件对应于用户id
		int uid = Integer.parseInt(acx.getSession().get("id").toString());
		String sql = "insert into file(uid, fileName) value(?,?)";
		ddDao.update(sql, uid,filePath.toString());
	}
}
